package com.btex.app;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.Application;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Process;
import android.support.multidex.MultiDex;

import com.alibaba.security.rp.RPSDK;
import com.baidu.mobstat.StatService;
import com.btex.app.push.XiaomiMessageReceiver;
import com.btex.app.push.XiaomiMessageReceiver.DemoHandler;
import com.btex.app.tools.SharedPreferencesUtil;
import com.lidroid.xutils.HttpUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheEntity;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.interceptor.HttpLoggingInterceptor;
import com.lzy.okgo.model.HttpHeaders;
import com.lzy.okgo.model.HttpParams;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.xiaomi.channel.commonutils.logger.LoggerInterface;
import com.xiaomi.mipush.sdk.Logger;
import com.xiaomi.mipush.sdk.MiPushClient;

import org.apache.http.client.HttpClient;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Level;

import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;


public class MyApplication extends Application {

    private static final String TAG = "MyApplication";
    private HashMap<String, Object> setting = new HashMap<String, Object>();

    private static MyApplication instance;
    //小米配置
    public static final String APP_ID = "2882303761517450017";
    public static final String APP_KEY = "5781745036017";
    private static DemoHandler handler = null;
    private static Context context;
    public static MyApplication mApp;
    private static HttpUtils httpUtils;
    private String mSessionids;
    private SharedPreferencesUtil mSharedPreferences;

    @Override
    public void onCreate() {
        super.onCreate();
        mApp = this;


        MultiDex.install(this);
        RPSDK.initialize(getApplicationContext());

        mSharedPreferences = SharedPreferencesUtil.getSharedPreferences(this);


        mSharedPreferences.putString("check", "0");
        mSharedPreferences.putString("checkTrade", "0");

        initOkgo();

//        StatService.setDebugOn(true);

        StatService.start(this);

        context = getApplicationContext();

        initImageLoader(getApplicationContext());

        //xiaomi
        // 注册push服务，注册成功后会向DemoMessageReceiver发送广播
        // 可以从DemoMessageReceiver的onCommandResult方法中MiPushCommandMessage对象参数中获取注册信息
        if (shouldInit()) {
            MiPushClient.registerPush(this, APP_ID, APP_KEY);
        }

        LoggerInterface newLogger = new LoggerInterface() {

            @Override
            public void setTag(String tag) {
                // ignore

            }

            @Override
            public void log(String content, Throwable t) {

            }

            @Override
            public void log(String content) {

            }
        };
        Logger.setLogger(this, newLogger);
        if (handler == null) {
            handler = new XiaomiMessageReceiver.DemoHandler(getApplicationContext());
        }


    }

    private void initOkgo() {


        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor("OkGo");
        //log打印级别，决定了log显示的详细程度
        loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);
        //log颜色级别，决定了log在控制台显示的颜色
        loggingInterceptor.setColorLevel(Level.INFO);
        builder.addInterceptor(loggingInterceptor);

        builder.cookieJar(new CookieJar() {
            @Override
            public void saveFromResponse(HttpUrl httpUrl, List<Cookie> cookies) {
                System.out.println("cookies url: " + httpUrl.toString());
                for (Cookie cookie : cookies) {
                    System.out.println("cookies: " + cookie.toString());
                }

            }

            @Override
            public List<Cookie> loadForRequest(HttpUrl httpUrl) {

                if (mSharedPreferences != null) {
                    mSessionids = mSharedPreferences.getString(Config.TOKEN, "");
                }
                ArrayList<Cookie> cookies = new ArrayList<>();

                Cookie cookie = new Cookie.Builder()
                        .hostOnlyDomain(httpUrl.host())
                        .name(Config.TOKEN).value(mSessionids)
                        .build();
                cookies.add(cookie);
                return cookies;

            }
        });

        SharedPreferencesUtil sharedPreferences = SharedPreferencesUtil.getSharedPreferences(this);
        boolean isEngilsh = sharedPreferences.getBoolean("isEngilsh", false);

        String lang = "";

        if (isEngilsh) {
            lang = "en";
        } else {
            lang = "zh_cn";
        }

        HttpHeaders headers = new HttpHeaders();
        headers.put("app-version", Config.VERSION);    //header不支持中文，不允许有特殊字符
        headers.put("channel", MyApplication.mApp.getApplicationMetaData("CXD_CHANNEL_ID"));
        headers.put("myclient", "android");
        headers.put("lang", lang);
        headers.put("source", "android");

        HttpParams params = new HttpParams();
        params.put("lang", lang);     //param支持中文,直接传,不要自己编码
        params.put("myclient", "android");     //param支持中文,直接传,不要自己编码
        OkGo.getInstance().init(this)                       //必须调用初始化
                .setOkHttpClient(builder.build())               //建议设置OkHttpClient，不设置将使用默认的
                .setCacheMode(CacheMode.NO_CACHE)               //全局统一缓存模式，默认不使用缓存，可以不传
                .setCacheTime(CacheEntity.CACHE_NEVER_EXPIRE)   //全局统一缓存时间，默认永不过期，可以不传
                .setRetryCount(3)                             //全局统一超时重连次数，默认为三次，那么最差的情况会请求4次(一次原始请求，三次重连请求)，不需要可以设置为0
                .addCommonHeaders(headers)
                .addCommonParams(params);
    }

    //返回
    public static Context getContextObject() {
        return context;
    }


    public void put(String key, Object object) {
        setting.put(key, object);
    }

    public Object get(String key) {
        return setting.get(key);
    }

    public static void initImageLoader(Context context) {
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
                .threadPriority(Thread.NORM_PRIORITY - 2)
                .denyCacheImageMultipleSizesInMemory()
                .diskCacheFileNameGenerator(new Md5FileNameGenerator())
                .diskCacheSize(50 * 1024 * 1024) // 50 Mb
                .tasksProcessingOrder(QueueProcessingType.LIFO)
//				.writeDebugLogs() // Remove for release app
                .build();
        ImageLoader.getInstance().init(config);
    }

    private boolean shouldInit() {
        ActivityManager am = ((ActivityManager) getSystemService(Context.ACTIVITY_SERVICE));
        List<RunningAppProcessInfo> processInfos = am.getRunningAppProcesses();
        String mainProcessName = getPackageName();
        int myPid = Process.myPid();
        for (RunningAppProcessInfo info : processInfos) {
            if (info.pid == myPid && mainProcessName.equals(info.processName)) {
                return true;
            }
        }
        return false;
    }

    public static DemoHandler getHandler() {
        return handler;
    }

    public String getApplicationMetaData(String valuve) {
        ApplicationInfo appInfo = null;
        try {
            appInfo = this.getPackageManager().getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        String ss = appInfo.metaData.getString(valuve);
        return ss;
    }


    public static HttpUtils get() {

        if (httpUtils != null) {

            return httpUtils;

        } else {

            httpUtils = new HttpUtils();
            HttpClient httpClient = httpUtils.getHttpClient();
            httpClient.getConnectionManager().closeExpiredConnections();
//            httpUtils.configRequestThreadPoolSize(6);

            return httpUtils;
        }


    }


}